import 'dart:async';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:haptic_feedback/haptic_feedback.dart';
import 'package:nfc_manager/nfc_manager.dart';
import 'package:barcode_scan2/barcode_scan2.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'restaurant.dart';

class RestaurantProvider with ChangeNotifier {
  ScanOptions scanOptions = const ScanOptions(
      android: AndroidOptions(
          aspectTolerance: 0.5, useAutoFocus: true), //(默认已配)添加Android自动对焦
      autoEnableFlash: false, //true打开闪光灯, false关闭闪光灯
      strings: {
        'cancel': '退出',
        'flash_on': '开闪光灯',
        'flash_off': '关闪光灯'
      } //标题栏添加闪光灯按钮、退出按钮
      );

  FlutterTts flutterTts = FlutterTts();
  AudioPlayer audioPlayer = AudioPlayer(); // 创建 AudioPlayer 实例

  RestaurantProvider() {
    audioPlayer.audioCache.prefix = 'assets/audio/';
    _initializeTts();
    _initializeNfc();
  }

  Future<void> _initializeTts() async {
    await flutterTts.setLanguage("zh-CN"); // 设置语言
    await flutterTts.setPitch(1.5); // 设置音调
    await flutterTts.setSpeechRate(0.5); // 设置语速
    await flutterTts.setVolume(1.0); // 设置音量
  }

  void _initializeNfc() {
    try {
      NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {
        // 处理NFC标签数据
        List<int> identifierValues =
            tag.data['nfca']['identifier'].reversed.toList();
        String nfcId = '';
        for (int i = 0; i < identifierValues.length; i++) {
          nfcId += identifierValues[i].toRadixString(16);
        }
        String decimalNfcId =
            int.parse(nfcId, radix: 16).toString().padLeft(10, '0');
        print(decimalNfcId);

        await flutterTts.speak("刷卡成功");
        // await flutterTts.stop();
      });
    } catch (e) {
      print(e);
    }
  }

  final List<Restaurant> _restaurants = [
    Restaurant(name: '餐厅A', totalMeals: 100, takenMeals: 50),
    Restaurant(name: '餐厅B', totalMeals: 150, takenMeals: 75),
  ];

  List<Restaurant> get restaurants => _restaurants;

  void switchRestaurant(int index) {
    // 切换餐厅逻辑
    notifyListeners();
  }

  void scanQRCode(BuildContext context) async {
    try {
      ScanResult result = await BarcodeScanner.scan(options: scanOptions);
      // 处理扫码结果
      if (context.mounted) {
        parseQRCodeResult(context, result.rawContent);
      }
    } catch (e) {
      if (context.mounted) {
        if (e is UnsupportedError) {
          TDToast.showFail('不支持扫码功能',
              direction: IconTextDirection.horizontal, context: context);
        }
        return;
      }
      print(e);
    }
    // 更新餐厅数据
    notifyListeners();
  }

  Future<void> parseQRCodeResult(BuildContext context, String content) async {
    if (content == '') {
      return;
    }
    final parts = content.split('|');
    if (parts.length == 2) {
      await playSound('scan.mp3');
      final cardNumber = parts[0];
      final timestamp = int.parse(parts[1]);
      final dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
      print('卡号: $cardNumber');
      print('时间: $dateTime');
      if (context.mounted) {
        TDLoadingController.show(context, text: "正在处理...");
        await flutterTts.speak("刷卡成功");
        await playSound('ding.mp3');
        TDLoadingController.dismiss();
      }
    } else {
      TDToast.showFail('无效的二维码',
          direction: IconTextDirection.horizontal, context: context);
    }
    print(parts);
  }

  Future<void> enterPhoneNumber(BuildContext context) async {
    var controller = TextEditingController();
    showGeneralDialog(
      context: context,
      pageBuilder: (BuildContext buildContext, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        return TDInputDialog(
          leftBtn: TDDialogButtonOptions(
            title: '取消',
            action: () => {Navigator.of(context).pop()},
          ),
          rightBtn: TDDialogButtonOptions(
              title: '确定',
              action: () async {
                if (controller.text.isEmpty) {
                  TDToast.showFail('内容不能为空',
                      direction: IconTextDirection.horizontal,
                      context: context);
                  return;
                }
                Navigator.of(context).pop();
                TDLoadingController.show(context, text: "正在处理...");
                await Haptics.vibrate(HapticsType.error);
                await playSound('ding.mp3');
                await flutterTts.speak("刷卡成功");
                TDLoadingController.dismiss();
              }),
          textEditingController: controller,
          title: '提示',
          hintText: '请输入手机号',
        );
      },
    );
  }

  Future<void> playSound(String fileName) async {
    Completer<void> completer = Completer<void>();
    try {
      await audioPlayer.play(AssetSource(fileName)); // 播放本地音频文件
      audioPlayer.onPlayerComplete.listen((event) {
        completer.complete();
      });
      await completer.future; // 等待音频播放完成
    } catch (e) {
      completer.completeError(e);
    }
  }
}
